/*
 * Filename:    EvaluationJob.java
 * Copyright:   2015 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2015-2-9
 */
package com.paic.mhis.hcpms.evaluation.common.biz.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.HospitalProviderOrgDTO;
import com.paic.mhis.hcpms.evaluation.common.biz.service.EvaluationCodeService;
import com.paic.mhis.hcpms.evaluation.common.biz.service.EvaluationJobService;
import com.paic.mhis.hcpms.evaluation.common.constants.EvaluationConstants;
import com.paic.mhis.hcpms.evaluation.common.dao.EvaluationJobDao;
import com.paic.mhis.hcpms.evaluation.common.dto.EvalRuleJobDTO;
import com.paic.mhis.hcpms.evaluation.common.dto.ExemptionUnitDTO;
import com.paic.mhis.hcpms.evaluation.common.dto.IntgrityEvalChildDTO;
import com.paic.mhis.hcpms.evaluation.common.dto.IntgrityEvalDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.KpiJobCtrlService;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.constants.CalculationJobConstants;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.HcpmsKpiJobCtrlDTO;
import com.pingan.um.client.util.UUID;

/**
 * 诚信考评JOB Service
 * 
 * @author EX-PANAN001
 */
@Component("evaluationJobService")
public class EvaluationJobServiceImpl implements EvaluationJobService {
	public static Log log = LogFactory.getLog(EvaluationJobServiceImpl.class);
	@Autowired
	private EvaluationJobDao evaluationJobDao;
	@Autowired
	private EvaluationCodeService evaluationCodeService;

	@Autowired
	private KpiJobCtrlService kpiJobCtrlService;

	/**
	 * 考评数据获取
	 */
	@Override
	@Transactional
	public void evaluaDataObtain() throws Exception {
		log.info("------------诚信考评JOB进入-----------");
		HcpmsKpiJobCtrlDTO ctrlDto = new HcpmsKpiJobCtrlDTO();
		ctrlDto.setJobCode("J20150308005");
		ctrlDto.setJobName("诚信考评JOB");
		ctrlDto.setJobStatus(CalculationJobConstants.CTRL_JOB_STATUS_USE);
		ctrlDto.setTmpId(UUID.getID());
		ctrlDto = kpiJobCtrlService.getHcpmsJobCtrl(ctrlDto);
		if (ctrlDto == null) {
			log.info("-----诚信考评JOB被占用-----");
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		// 数据库取到时间就用数据库的时间没有取到就用当前时间
		String date = evaluationJobDao.queryJobTime(EvaluationConstants.JOB_TYPE);
		if (StringUtils.isEmpty(date)) {
			date = sdf.format(new Date());
		}
		// 获取所有机构
		List<HospitalProviderOrgDTO> providers = evaluationJobDao.getProviderInfo();

		// 获取考评规则
		List<EvalRuleJobDTO> queryEvalRule = evaluationJobDao.queryEvalRule(date);
		// 存储 医院规则
		List<EvalRuleJobDTO> hospitalRule = new ArrayList<EvalRuleJobDTO>();
		// 存储 药店规则
		List<EvalRuleJobDTO> drugstoreRule = new ArrayList<EvalRuleJobDTO>();
		boolean flag = setEvalRules(queryEvalRule, hospitalRule, drugstoreRule);
		if (flag) {
			addIntgrityData(date, providers, hospitalRule, drugstoreRule);
		} else {
			log.info("---------没有可用考评规则的数据----------");
		}
		log.info("--------------诚信考评JOB结束------------");
		ctrlDto.setJobStatus(CalculationJobConstants.CTRL_JOB_STATUS_IDLE);
		ctrlDto.setTmpId(null);
		kpiJobCtrlService.updateHcpmsJobCtrl(ctrlDto);
	}

	/**
	 * 诚信考评规则分类型存储
	 * 
	 * @param queryEvalRule
	 * @param hospitalRule
	 * @param drugstoreRule
	 */
	private boolean setEvalRules(List<EvalRuleJobDTO> queryEvalRule, List<EvalRuleJobDTO> hospitalRule,
			List<EvalRuleJobDTO> drugstoreRule) {
		if (null != queryEvalRule && queryEvalRule.size() > 0) {
			for (EvalRuleJobDTO eJobDTO : queryEvalRule) {
				if (eJobDTO.getRuleType().equals(EvaluationConstants.HOSPITAL_RULE)) {
					hospitalRule.add(eJobDTO);
				} else if (eJobDTO.getRuleType().equals(EvaluationConstants.DRUGSTORE_RULE)) {
					drugstoreRule.add(eJobDTO);
				}
			}
			return true;
		} else {
			return false;
		}

	}

	private void addIntgrityData(String date, List<HospitalProviderOrgDTO> providers,
			List<EvalRuleJobDTO> hospitalRule, List<EvalRuleJobDTO> drugstoreRule) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null != providers && providers.size() > 0) {
			for (HospitalProviderOrgDTO provider : providers) {
				map.put("orgCode", provider.getProviderCode());
				map.put("date", date);
				int time = Integer.parseInt(date);
				map.put("timeOne", (time - 1) + "");
				map.put("timeTwo", (time - 2) + "");
				// 校验机构在本年度是否已经有过数据操作
				List<IntgrityEvalDTO> IntgrityEvals = evaluationJobDao.queryIntgrityEval(map);
				if (null != IntgrityEvals && IntgrityEvals.size() > 0) {
					evaluationJobDao.updateIntgrityEvalChild(map);
					evaluationJobDao.updateIntgrityEval(map);
				}
				// 生成考评编号
				String evaluationCode = evaluationCodeService.getEvaluationCode(EvaluationConstants.CODE_TYPE,
						EvaluationConstants.PREFIX_STR, date);
				IntgrityEvalDTO IntrityEval = setIntrityEval(date, provider, evaluationCode);
				// 判断当前机构属于医疗机构还是药店
				if (null != provider.getProvidertype()
						&& provider.getProvidertype().equals(EvaluationConstants.HOSPITAL_TYPE) && null != hospitalRule
						&& hospitalRule.size() > 0) {
					addHospital(hospitalRule, provider, IntrityEval);
					evaluationJobDao.addIntgrityEval(IntrityEval);
					// =======新增医院免考单位=====================
					addHospitaExemption(date, map, provider);

				} else {
					log.info("-----医疗机构类型与考评规则不匹配或者没有可用医疗机构考评规则的数据-----");
				}
				if (null != provider.getProvidertype()
						&& provider.getProvidertype().equals(EvaluationConstants.DRUGSTORE_TYPE)
						&& null != drugstoreRule && drugstoreRule.size() > 0) {
					addDrugstore(drugstoreRule, IntrityEval);
					evaluationJobDao.addIntgrityEval(IntrityEval);
					map.put("score", EvaluationConstants.SCORE_TWO);
					// =======新增药店免考单位=====================
					addExemptionUnit(date, map);

				} else {
					log.info("-----药店类型与考评规则不匹配或者没有可用定点药店考评规则的数据-----");
				}

			}

		} else {
			log.info("----------------没有可用考评机构的数据------------");
			return;
		}
	}

	/**
	 * 新增机构免考单位
	 * 
	 * @param date
	 * @param map
	 * @param provider
	 */
	private void addHospitaExemption(String date, Map<String, Object> map, HospitalProviderOrgDTO provider) {
		if (null != provider.getBednum() && provider.getBednum().intValue() > 0) {
			map.put("score", EvaluationConstants.SCORE_ONE);
			addExemptionUnit(date, map);
		} else {
			map.put("score", EvaluationConstants.SCORE_TWO);
			addExemptionUnit(date, map);
		}
	}

	/**
	 * 公用免考新增
	 * 
	 * @param date
	 * @param map
	 */
	private void addExemptionUnit(String date, Map<String, Object> map) {
		int rtn = evaluationJobDao.queryExemptionUnit(map);
		if (rtn >= 2) {
			ExemptionUnitDTO unitDTO = new ExemptionUnitDTO();
			unitDTO.setOrgCode(map.get("orgCode").toString());
			unitDTO.setExemptionDate(date);
			evaluationJobDao.addExemptionUnit(unitDTO);
		}
	}

	/**
	 * 新增诚信子表机构规则信息
	 * 
	 * @param hospitalRule
	 * @param provider
	 * @param IntrityEval
	 */
	private void addHospital(List<EvalRuleJobDTO> hospitalRule, HospitalProviderOrgDTO provider,
			IntgrityEvalDTO IntrityEval) {
		for (EvalRuleJobDTO eJobDTO : hospitalRule) {
			IntgrityEvalChildDTO ieChilDto = null;
			// 床位数大于0 执行全部规则 反之不执行住院规则
			if (null != provider.getBednum() && provider.getBednum().intValue() > 0) {
				ieChilDto = setIntgrityEvalChild(IntrityEval, eJobDTO);
			} else {
				if (!eJobDTO.getBusinessType().equals(EvaluationConstants.BUSINESS_TYPE_STAY)) {
					ieChilDto = setIntgrityEvalChild(IntrityEval, eJobDTO);
				}
			}

			if (null != ieChilDto) {
				evaluationJobDao.addIntgrityEvalChild(ieChilDto);
			}
		}
	}

	/**
	 * 新增诚信子表药店规则信息
	 * 
	 * @param drugstoreRule
	 * @param IntrityEval
	 */
	private void addDrugstore(List<EvalRuleJobDTO> drugstoreRule, IntgrityEvalDTO IntrityEval) {
		for (EvalRuleJobDTO Rule : drugstoreRule) {
			IntgrityEvalChildDTO IntgrityEvalChild = setIntgrityEvalChild(IntrityEval, Rule);
			evaluationJobDao.addIntgrityEvalChild(IntgrityEvalChild);
		}
	}

	/**
	 * 封装考评子表信息
	 * 
	 * @param iedto
	 * @param eJobDTO
	 */
	private IntgrityEvalChildDTO setIntgrityEvalChild(IntgrityEvalDTO iedto, EvalRuleJobDTO eJobDTO) {
		IntgrityEvalChildDTO iedChildto = new IntgrityEvalChildDTO();
		iedChildto.setEvaluationCode(iedto.getEvaluationCode());
		iedChildto.setEvalRuleId(eJobDTO.getEvalRuleId());
		iedChildto.setEvaluationAllScore(eJobDTO.getSumGrade());
		iedChildto.setEvaluationScroe(eJobDTO.getSumGrade());
		iedChildto.setIsValid(EvaluationConstants.ISVALID);
		iedChildto.setCreatedBy(EvaluationConstants.USERBY);
		iedChildto.setUpdatedBy(EvaluationConstants.USERBY);
		return iedChildto;
	}

	/**
	 * 封装诚信考评信息
	 * 
	 * @param sdf
	 * @param provider
	 * @param evaluationCode
	 * @return
	 */
	private IntgrityEvalDTO setIntrityEval(String date, HospitalProviderOrgDTO provider, String evaluationCode) {
		IntgrityEvalDTO iedto = new IntgrityEvalDTO();
		iedto.setEvaluationCode(evaluationCode);
		iedto.setEvaluationAllScore(new BigDecimal(0));
		iedto.setEvaluationYear(date);
		iedto.setEvalautionType(provider.getProvidertype());
		iedto.setOrgCode(provider.getProviderCode());
		iedto.setStatus(EvaluationConstants.STATUSONE);
		iedto.setIsValid(EvaluationConstants.ISVALID);
		iedto.setCreatedBy(EvaluationConstants.USERBY);
		iedto.setUpdatedBy(EvaluationConstants.USERBY);
		return iedto;
	}

}
